const Subscription = require('egg').Subscription;

class ScanTasksGroup extends Subscription {
  // 每30秒执行一次
  static get schedule() {
    return {
      interval: '10s',
      type: 'worker',
    };
  }

  // 群发任务
  async subscribe() {
    const { ctx, service } = this;
    const now = new Date();
    const startTime = new Date(now.getTime() - 10000 + 8 * 60 * 60 * 1000); // 提前10秒开始扫描
    const endTime = new Date(now.getTime() + 10000 + 8 * 60 * 60 * 1000); // 包含未来10秒的任务

    const tasks = await ctx.model.Sendallcontent.find({
      triggerTime: { $gte: startTime, $lte: endTime },
      istask: true,
      status: 0, // 只处理未发送的任务
    }).limit(100);

    if (tasks.length === 0) {
      ctx.logger.info("该时间没有群发任务");
      return;
    }

    for (const task of tasks) {
      try {
        // 根据 msgtype 调用不同的发送方法
        let result = {};
      switch(task.msgtype) {
        case 'text':
          result = await service.sendmsg.sendText2(task.wxid, task.content, task.ownerWxid);
          break;
        case 'image':
          result = await service.sendmsg.sendImage(task.wxid, task.path, task.ownerWxid);
          break;
        case 'file':
          result = await service.sendmsg.sendFile(task.wxid, task.path, task.ownerWxid);
          break;
        case 'gh':
          result = await service.sendmsg.sendApplet(task.wxid, task.gh, task.ownerWxid);
          break;
        case 'share':
          result = await service.sendmsg.sendShareUrl(task.wxid, task.jumpUrl, task.ownerWxid);
          break;
        default:
          ctx.logger.warn(`未知的消息类型: ${task.msgtype}`);
          continue;
      }

      if (result.code === 200) {
        await ctx.model.Sendallcontent.updateOne(
          { _id: task._id },
          { $set: { status: 1 } }
        );
        ctx.logger.info(`✅ 发送成功: ${task.msgtype}`);
      } else {
        await ctx.model.Sendallcontent.updateOne(
          { _id: task._id },
          { $set: { status: 2 } }
        );
        ctx.logger.error(`❌ 发送失败: ${result.msg}`);
      }
      } catch (error) {
        ctx.logger.error(`❌ 处理任务 ${task._id} 出现异常:`, error);
      }
    }
  }
}

module.exports = ScanTasksGroup;
